<?php

namespace Com\Fetch;


class Fetch{
    private  $url = '';
    private  $content = '';
    private $dom = '';

    public function __construct(){
        require_once __DIR__."/src/Furl.php";
        require_once __DIR__.'/src/FEncode.php';
        require_once __DIR__."/src/FDom.php";

        $this->dom = new FDom();
    }

    /**
     * 设置url并抓取 对应的页面，并对页面进行编码设置
     * @param $url
     */
    public function set($url,$post_data){
        try{
            if(empty($url)){
                throw  new \Exception('The request url is not allowed empty');
            }
            $this->url = $url;
            $this->content = $this->get($post_data);
            $this->content = (new FEncode())->encode($this->content);
        }catch (\Exception $e){
            echo $e->getMessage();
        }
    }
    /**
     * 设置url并抓取 对应的页面，并对页面进行编码设置
     * @param $url
     */
    public function setContent($content=''){
        try{
            $this->content = $content;
            $this->content = (new FEncode())->encode($this->content);
        }catch (\Exception $e){
            echo $e->getMessage();
        }
    }

    /**
     * 抓取页面
     *
     * @return bool|mixed
     * @throws \Exception
     */
    private function get($post_data){

        if(! empty($this->url)){
            $url = new Furl();
            $content = $url->request($this->url,$post_data);

            if($content){
                return $content;
            }else{
                throw new \Exception("your request url`s content is empty");
            }
        }else{
            throw new \Exception('please use fetch->set(your request url) setting the request url');
        }
    }

    /*
     * 按id抓取页面的数据，opt可选value和element
     * value：只抓取文本
     * element：抓起html内容
     * 返回字符串
     */
    public function id($id,$opt='value'){
        return  $this->dom->id($this->content,$id,$opt);
    }

    /*
     * 按class抓取页面的数据，opt可选value和element
     * value：只抓取文本
     * element：抓起html内容
     * 返回数组
     */
    public function clas($class,$opt='value'){
        return $this->dom->clas($this->content,$class,$opt);
    }

    /**
     * @param $ele
     * @param string $opt
     * @return bool|string
     * 按标签名抓取页面的数据，opt可选value和element
     * value：只抓取文本
     * element：抓起html内容
     * 返回数组
     */
    public function ele($ele,$opt='value'){
        return $this->dom->ele($this->content,$ele,$opt);
    }

    /**
     * @param $str
     * @param string $opt
     * @return array|bool
     *
     * 组合抓取   类似jquery的选择器 .class > #id > element
     *
     * opt可选value和element
     */
    public function query($str,$opt="value"){
        return $this->dom->query($this->content,$str,$opt);
    }

    /**
     * @param $str
     * @param $attr
     * @return array
     * 
     * 组合抓取 类似jquery的选择器 .class > #id > element
     *  opt可选value和element
     */
    public function query_attr($str,$attr){
        return $this->dom->query_attr($this->content,$str,$attr);
    }
}